<template>
  <div style="width:100%" class="examination">
    <!-- 出题和答题的转换 -->
    <div v-if="isManager && !isDesigner">
      <el-divider>题目
        <el-tooltip content="切换出题" placement="top">
          <i class="el-icon-turn-off switch-btn" @click="switchtTopic()"></i>
        </el-tooltip>
      </el-divider>
    </div>
    <!-- 设计模式 -->
    <div v-if="isDesigner">
      <div v-for="(topic, index) in examList">
        <p>
          {{index + 1}}、{{ topic.question }}
          <span v-if="topic.required == true"> (必填)</span>
        </p>
        <div class="q_options">
          <el-radio-group v-model="radio">
            <el-radio v-for="(option, optionIndex) in topic.options.split('&')" :key="optionIndex" :label="optionIndex + 1">{{ option }}</el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>
    <!-- 答案总结 -->
    <div v-else-if="isResult">
      <el-form label-position="top" class="demo-dynamic">
        <el-form-item
          v-for="(topic, index) in topicList"
          :key="index"
        >
          <span slot="label">
            {{ index+1 + '、' + topic.question }}
            <span v-if="topic.required == true"> (必填)</span>
          </span>
          <div v-if="topic.type === 'textarea'" class="a_options w-100">
            <el-row v-for="(option, optionIndex) in topic.options.split('&')" :key="optionIndex">
              <el-col>
                ({{ optionIndex + 1 }})、
                <span>{{ option }}</span>
              </el-col>
            </el-row>
          </div>
          <div v-else-if="topic.type === 'radio'" class="a_options w-100">
            <el-row v-for="(option, optionIndex) in topic.options.split('&')" :key="optionIndex">
              <el-col :xs="14" :sm="14" :md="14" :lg="10" :xl="8">
                <img src="./radio.svg" style="height: 14px;margin: 10px 10px 0 0;">
                <span>{{ option.split(':')[0] }}</span>
              </el-col>
              <el-col :xs="10" :sm="10" :md="10" :lg="14" :xl="16">
                  <span>{{ option.split(':')[1] }}</span>
              </el-col>
            </el-row>
          </div>
          <div v-else-if="topic.type === 'checkbox'" class="a_options w-100">
            <el-row v-for="(option, optionIndex) in topic.options.split('&')" :key="optionIndex">
              <el-col :xs="14" :sm="14" :md="14" :lg="10" :xl="8">
                <img src="./checkbox.svg" style="height: 14px;margin: 0px 10px 0px 0px;">
                <span>{{ option.split(':')[0] }}</span>
              </el-col>
              <el-col :xs="10" :sm="10" :md="10" :lg="14" :xl="16">
                  <span>{{ option.split(':')[1] }}</span>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!-- 出题模式 -->
    <div v-else-if="isManager && !isWriting && mixEditable">
      <draggable
        :list="topicList"
        :animation="340"
        group="selectItem"
        handle=".option-drag"
      >
        <div
          v-for="(item, index) in topicList"
          :key="index"
          class="select-item"
        >
          <div class="select-line-icon option-drag">
            <!-- <i class="el-icon-s-operation" /> -->
            {{ index + 1 }}、
          </div>
          <el-input type="textarea" v-model="item.question" style="width: calc(100% - 60px)"></el-input>
          <div
            class="delete-btn"
            @click="topicList.splice(index, 1)"
          >
            <i class="el-icon-delete" />
          </div>
          <div v-if="item.type !== 'textarea' && optionArr[index]" style="width: 100%;">
            <div class="q_options ml-30" v-for="(option, i) in optionArr[index]">
              <!-- option -->
              <img v-if="item.type === 'radio'" src="./radio.svg" style="height: 13px;margin: 10px 10px 0 0;">
              <img v-else src="./checkbox.svg" style="height: 15px;margin: 7px 10px 0 0;">
              <el-input v-model="optionArr[index][i]" style="width: 100%;"></el-input>
              <i class="el-icon-circle-plus-outline action" @click="addOptions(optionArr[index])" />
              <i class="el-icon-remove-outline action" @click="optionArr[index].length <= 1 ? '' : optionArr[index].splice(i, 1)" />
            </div>
          </div>
          
          <div style="width: 100%;" class="ml-30">
            <!-- 必填 -->
            <el-checkbox v-model="item.required">必填</el-checkbox>
          </div>
        </div>
      </draggable>
      <div class="ml-30">
        <el-dropdown @command="addTopic" class="addTopic">
        <el-button icon="el-icon-plus" style="width: 100%;">
          添加题目<i class="el-icon-arrow-down el-icon--right fr"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="radio">单选</el-dropdown-item>
          <el-dropdown-item command="checkbox">多选</el-dropdown-item>
          <el-dropdown-item command="textarea">填空题</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      </div>
      <!-- <el-divider /> -->
    </div>
    <!-- 答题模式 -->
    <div v-else>
      <el-form :model="valueObj" ref="examinationForm" :disabled="!mixEditable" label-position="top" class="demo-dynamic">
        <el-form-item
          v-for="(topic, index) in topicList"
          :key="index"
          :prop="String(index)"
          :rules="{
            required: topic.required, message: '此题不能为空', trigger: 'blur'
          }"
        >
          <span slot="label">
            {{ index+1 + '、' + topic.question }}
            <span v-if="topic.required == true"> (必填)</span>
          </span>
          <div v-if="topic.type === 'textarea'" class="a_options w-100">
            <el-input type="textarea" v-model="valueObj[String(index)]" style="width: 100%;"></el-input>
          </div>
          <div v-else-if="topic.type === 'radio'" class="a_options w-100">
            <el-radio-group v-model="valueObj[String(index)]">
              <el-radio v-for="(option, optionIndex) in topic.options.split('&')" :key="optionIndex" :label="String(optionIndex + 1)">{{ option }}</el-radio>
            </el-radio-group>
          </div>
          <div v-else-if="topic.type === 'checkbox'" class="a_options w-100">
            <el-checkbox-group v-model="valueObj[String(index)]">
              <el-checkbox v-for="(option, optionIndex) in topic.options.split('&')" :key="optionIndex" :label="String(optionIndex + 1)">{{ option }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { isArray, debounce, cloneDeep } from 'lodash'
export default {
  name: 'examination',
  props: {
    // field
    value: '',
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    DefaultTopicList: {
      type: Array,
      default: () => []
    },
    // 修改题目权限
    isManager: {
      type: Boolean,
      default: false
    },
    isResult: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    isDesigner(){
      return this.$attrs._source === 'designer'
    },
    mixEditable() {
      return !(this.$attrs.readonly || this.$attrs.disabled) && this.mode === "edit"
    },
  },
  data() {
    return {
      // 每道题答案
      separator: '@',
      // 多选选项
      multipleSeparator: '&',
      topicList: [],
      radio: '',
      checkList: [],
      isWriting: !this.isManager,
      examList: [{
        type: 'radio',
        question: '单选',
        options: 'A&B&C&D',
        required: true
      }],
      valueObj: {},
      optionArr: []
    }
  },
  mounted(){
    this.optionArr = isArray(this.topicList) && this.topicList.map(v =>v.options && v.options.split(this.multipleSeparator) || [''])
    // this.formatModel()
  },
  watch: {
    valueObj: {
      immediate: true,
      deep: true,
      handler(val) {
        let value = ''
        for(const v in val) {
          const temp = val[v] && isArray(val[v]) ? val[v].join(this.multipleSeparator) : val[v]
          value = v == 0 ? temp : value + this.separator + temp
        }
        this.$emit('input', value)
      }
    },
    optionArr: {
        immediate: true,
        deep: true,
        handler(val, oldval) {
          if (oldval !== undefined && this.topicList && isArray(this.topicList)) {
            this.topicList = this.topicList.map((item, index) => {
              if (item.type !== 'textarea') {
                item.options = val[index] && val[index].join(this.multipleSeparator)
              }
              return item
            })
          }
        }
      },
    DefaultTopicList: {
      immediate: true,
      deep: true,
      handler(val, oldValue) {
        this.topicList = cloneDeep(val)
        this.formatModel()
      }
    }
  },
  methods: {
    // 格式化答题数据
    formatModel() {
      let form = {}
      if (!this.value) {
        this.topicList && this.topicList.forEach((v, i) => form[String(i)]= v.type === 'checkbox' ? [] : '')
      } else {
        const valueArr = this.value && this.value.split(this.separator)
        this.topicList && this.topicList.forEach((v, i) => {
          form[String(i)]= (v.type === 'checkbox' ? valueArr[i] && valueArr[i].split(this.multipleSeparator) || [] : valueArr[i] || '')
        })
      }
      this.$set(this, 'valueObj', cloneDeep(form))
    },

    // 题目相关方法
    addTopic(type) {
      console.log(type,'====type')
      this.topicList.push({
        type,
        question: '',
        options: '', //分隔符&
        required: false
      })
      this.optionArr = this.topicList.map(v =>v.options && v.options.split(this.multipleSeparator) || [''])
      console.log(this.optionArr,'====optionArr')
    },
    addOptions(data) {
      console.log('addOptions',data)
      data.push('')
    },

    // 返回题目
    async switchtTopic() {
      this.isWriting = !this.isWriting
      if (this.isWriting) {
        this.$emit('createSuccess', this.topicList)
        // this.deb(this, this.topicList)
        this.formatModel()
        return this.topicList
      }
    },

    // 返回题目和答案
    getAnswer() {
      let list = cloneDeep(this.topicList)
      for(const v in this.valueObj) {
        list[Number(v)].answer = isArray(this.valueObj[v])  ? this.valueObj[v].join(this.multipleSeparator) : this.valueObj[v]
      }
      return list
    }
  }
}
</script>
<style lang="scss" scoped>
// a_回答 q_问题
  .examination {
    .switch-btn {
      cursor: pointer;
      color: deepskyblue;
    }
    .a_options {
      padding-left: 22px;
    }
  }
  label.el-checkbox, label.el-radio {
    display: block;
  }
  label.el-radio {
    height: 28px;
  }
  .w-100 {
    width: 100%;
  }

.select-item {
  display: flex;
  flex-wrap: wrap;
  border: 1px dashed #fff;
  box-sizing: border-box;
  padding: 2px 0px;
  & .delete-btn {
    cursor: pointer;
    // color: #f56c6c;
    font-size: 20px;
    color: #b6b2b2;
    line-height: 35px;
    margin-left: 5px;
  }
  & .el-input + .el-input {
    margin-left: 4px;
  }
  &:hover {
    background: #efefef;
  }
  .select-line-icon {
    line-height: 32px;
    font-size: 16px;
    padding: 0 4px;
    color: #777;
  }
  .option-drag {
    cursor: move;
  }
  .q_options {
    display: flex;
    /* width: 75%; */
    margin-top: 9px;
    padding-right: 100px;
    min-width: 50%;
    max-width: 90%;
    .el-input {
      flex: 1;
    }
    .action {
      cursor: pointer;
      line-height: 30px;
      margin: 0 5px;
      font-size: 20px;
      color: #b6b2b2;
    }
  }
}
.ml-30 {
  margin-left: 30px;
}
.addTopic {
  width: 100%;
  margin-top: 5px;
}
.isresult {
  width: 100%;
  display: flex;
  div {
    flex: 1;
    margin-right: 10px;
  }
}
</style>